﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web.Script.Serialization;
using AirIndex.Models.HtmlClient.SendData;
using HVACWebService.Common;

namespace HVACWebService.Cloud.WeChat
{
    /// <summary>
    /// AccessToken 的摘要说明
    /// </summary>
    public class WeiXinToken
    {
        #region 获取微信凭证

        public static string GetAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";


        //public static string getAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&grant_type=authorization_code";

        public string GetAccessToken()
        {

            var accessToken = "";
            string appId = ConfigHelper.GetValue<string>("AppId");
            string appSecret =  ConfigHelper.GetValue<string>("AppSecret");

            //获取配置信息Datatable

            string respText = "";
            //获取appid和appsercret
            string wechat_appid = appId;
            string wechat_appsecret = appSecret;
            //获取josn数据
            string url = string.Format(GetAccessTokenUrl, wechat_appid, wechat_appsecret);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            using (Stream resStream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(resStream, Encoding.Default);
                respText = reader.ReadToEnd();
                resStream.Close();
            }
            JavaScriptSerializer Jss = new JavaScriptSerializer();
            Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(respText);
            accessToken = respDic["access_token"].ToString();
            return accessToken;
        }

        string jsapiUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi";

        public string GetJsApiTicket(string accessToken)
        {
            var jsToken = "";

                string respText = "";

                //获取josn数据
                string url = string.Format(jsapiUrl, accessToken);

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                using (Stream resStream = response.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(resStream, Encoding.Default);
                    respText = reader.ReadToEnd();
                    resStream.Close();
                }
                JavaScriptSerializer Jss = new JavaScriptSerializer();
                Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(respText);
                //通过键access_token获取值
                jsToken = respDic["ticket"].ToString();
                return jsToken;
        }

        #endregion 获取微信凭证


        #region 计算签名

        public Tokens GetTokens(string accessToken, string jsapi, string soureUrl)
        {
            var nonce = GenerateRandomString(16);
            var timestamp = DateTimeToStamp(DateTime.Now);
            var signatureStr = "jsapi_ticket=" + jsapi + "&noncestr=" + nonce + "&timestamp=" + timestamp + "&url=" + soureUrl;
            var signature = GetUserSignature(signatureStr);
            return new Tokens
            {
                appId = ConfigHelper.GetValue<string>("AppId"),
                appSecret = ConfigHelper.GetValue<string>("AppSecret"),
                JsApiTicket = jsapi,
                nonce = nonce,
                timestamp = timestamp,
                signature = signature
            };
        }

        static Random random = new Random();
        static string GenerateRandomString(int length)
        {
            var chars = "ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";

            StringBuilder result = new StringBuilder();

            for (int i = 0; i < length; i++)
            {
                int index = random.Next(chars.Length);
                result.Append(chars[index]);
            }

            return result.ToString();
        }
        private int DateTimeToStamp(DateTime time)
        {
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }

        static public string GetUserSignature(string strSha1In)
        {
            SHA1 sha1 = new SHA1CryptoServiceProvider();
            var bytesSha1In = Encoding.Default.GetBytes(strSha1In);
            var bytesSha1Out = sha1.ComputeHash(bytesSha1In);
            var strSha1Out = BitConverter.ToString(bytesSha1Out);
            return strSha1Out.Replace("-", "").ToLower();
        }
        #endregion


    }



}